package ru.stepuk.modern.nodes;

import javax.swing.JDialog;
import ru.stepuk.modern.InvalidModelException;
import javax.swing.ImageIcon;
import org.apache.commons.collections15.Factory;
import ru.stepuk.modern.Model;
import ru.stepuk.modern.Request;
import ru.stepuk.modern.Timeline;
import ru.stepuk.modern.distributions.Distribution;
import ru.stepuk.modern.events.RequestCreation;
import ru.stepuk.modern.gui.SetDistributionDialog;
import ru.stepuk.modern.gui.SetPopulationDialog;

/**
 *
 * @author ivan
 */
public class Source extends Node implements DistributionDependent, Factory<Request> {

    private int population;
    private int created = 0;
    private Distribution distribution;
    private Timeline timeline;
    private double lastCreationTime;
    private Node next;

    {
        name = "Source_" + getId();
    }

    public Source(Model model, Distribution distribution, Timeline timeline) {
        super(model);
        this.distribution = distribution;
        this.timeline = timeline;
        changeIcon();
    }

    public Distribution getDistribution() {
        return distribution;
    }

    public void setDistribution(Distribution distribution) {
        this.distribution = distribution;
        changeIcon();
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public void changeIcon() {
        icon = new ImageIcon(getClass().getResource("/images/s_" + distribution.toString() + ".png"));
    }

    public void setCreationEvent() {
        created++;
        lastCreationTime += distribution.nextValue();
        timeline.addEvent(lastCreationTime, new RequestCreation(this));
        
    }

    @Override
    public void processRequest(Request request) {
        System.out.println(timeline.now() + ": " + name + "request created");
        next.processRequest(request);
    }

    public JDialog getPropertiesDialog() {
        return new SetDistributionDialog(this, true);
    }

    public JDialog getPopulationDialog() {
        return new SetPopulationDialog(this);
    }

    public Request create() {
        if ((population == 0) || (created < population)) {
            setCreationEvent();
        }
        
        return new Request();
    }

    public void validate() throws InvalidModelException {
        created = 0;
        lastCreationTime = 0;

        if (!model.getIncome(this).isEmpty()) {
            throw new InvalidModelException(name + ": Income to source");
        }

        if (model.getNextNodes(this).size() > 1) {
            throw new InvalidModelException(name + ": Not single out from source ");
        }
        
        if (model.getNextNodes(this).size() == 0) {
            throw new InvalidModelException(name + ": No output from source ");
        } else {
            next = model.getNextNodes(this).toArray(new Node[0])[0];
        }
    }
}
